<template>
  <div class="finance-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>财务管理</span>
        </div>
      </template>
      
      <!-- 财务概览 -->
      <el-row :gutter="20" class="finance-overview">
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="overview-header">
                <span>今日收入</span>
                <el-tag type="success">实时</el-tag>
              </div>
            </template>
            <div class="overview-content">
              <div class="amount">¥ {{ todayIncome }}</div>
              <div class="compare">
                较昨日
                <span :class="incomeCompare >= 0 ? 'up' : 'down'">
                  {{ Math.abs(incomeCompare) }}%
                  <el-icon><component :is="incomeCompare >= 0 ? 'ArrowUp' : 'ArrowDown'" /></el-icon>
                </span>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="overview-header">
                <span>本月收入</span>
              </div>
            </template>
            <div class="overview-content">
              <div class="amount">¥ {{ monthIncome }}</div>
              <div class="compare">
                较上月
                <span :class="monthCompare >= 0 ? 'up' : 'down'">
                  {{ Math.abs(monthCompare) }}%
                  <el-icon><component :is="monthCompare >= 0 ? 'ArrowUp' : 'ArrowDown'" /></el-icon>
                </span>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="overview-header">
                <span>待处理发票</span>
              </div>
            </template>
            <div class="overview-content">
              <div class="amount">{{ pendingInvoices }}</div>
              <div class="compare">待处理</div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="overview-header">
                <span>待缴税款</span>
              </div>
            </template>
            <div class="overview-content">
              <div class="amount">¥ {{ pendingTax }}</div>
              <div class="compare">待缴纳</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 功能模块导航 -->
      <el-row :gutter="20" class="module-nav">
        <el-col :span="8">
          <el-card shadow="hover" @click="handleModuleClick('income')">
            <div class="module-item">
              <el-icon><Money /></el-icon>
              <span>收入管理</span>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="hover" @click="handleModuleClick('tax')">
            <div class="module-item">
              <el-icon><Document /></el-icon>
              <span>税务管理</span>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card shadow="hover" @click="handleModuleClick('invoice')">
            <div class="module-item">
              <el-icon><Tickets /></el-icon>
              <span>发票管理</span>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 收入趋势图 -->
      <el-card class="chart-card">
        <template #header>
          <div class="card-header">
            <span>收入趋势</span>
            <el-radio-group v-model="chartTimeRange" size="small">
              <el-radio-button label="week">本周</el-radio-button>
              <el-radio-button label="month">本月</el-radio-button>
              <el-radio-button label="year">本年</el-radio-button>
            </el-radio-group>
          </div>
        </template>
        <div class="chart-container" ref="incomeChartRef"></div>
      </el-card>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { Money, Document, Tickets, ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { getFinanceOverview, getIncomeTrend } from '@/api/wash_service'

const router = useRouter()
const incomeChartRef = ref(null)
let incomeChart = null

// 财务概览数据
const todayIncome = ref(0)
const monthIncome = ref(0)
const pendingInvoices = ref(0)
const pendingTax = ref(0)
const incomeCompare = ref(0)
const monthCompare = ref(0)

// 图表时间范围
const chartTimeRange = ref('week')

// 获取财务概览数据
const fetchFinanceOverview = async () => {
  try {
    const res = await getFinanceOverview()
    if (res && (res.code === 200 || res.data)) {
      const data = res.data || res
      todayIncome.value = data.todayIncome || 0
      monthIncome.value = data.monthIncome || 0
      pendingInvoices.value = data.pendingInvoices || 0
      pendingTax.value = data.pendingTax || 0
      incomeCompare.value = data.incomeCompare || 0
      monthCompare.value = data.monthCompare || 0
    }
  } catch (error) {
    console.error('获取财务概览数据失败:', error)
    // 重置为默认值
    todayIncome.value = 0
    monthIncome.value = 0
    pendingInvoices.value = 0
    pendingTax.value = 0
    incomeCompare.value = 0
    monthCompare.value = 0
  }
}

// 初始化收入趋势图
const initIncomeChart = async () => {
  if (!incomeChartRef.value) return
  
  incomeChart = echarts.init(incomeChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: [],
      type: 'line',
      smooth: true,
      areaStyle: {}
    }]
  }
  
  incomeChart.setOption(option)
  
  // 获取收入趋势数据
  try {
    const res = await getIncomeTrend({ timeRange: chartTimeRange.value })
    if (res && (res.code === 200 || res.data)) {
      const data = res.data || res
      incomeChart.setOption({
        xAxis: {
          data: data.dates || []
        },
        series: [{
          data: data.amounts || []
        }]
      })
    }
  } catch (error) {
    console.error('获取收入趋势数据失败:', error)
    // 设置空数据
    incomeChart.setOption({
      xAxis: {
        data: []
      },
      series: [{
        data: []
      }]
    })
  }
}

// 监听图表时间范围变化
watch(chartTimeRange, () => {
  initIncomeChart()
})

// 模块点击跳转
const handleModuleClick = (module) => {
  const routeMap = {
    income: '/finance/income',
    tax: '/finance/report', // 税务管理暂时跳转到财务报表
    invoice: '/finance/settlement' // 发票管理暂时跳转到结算管理
  }
  
  const route = routeMap[module]
  if (route) {
    router.push(route)
  } else {
    // 如果路由不存在，跳转到对应的财务子页面
    router.push(`/finance/${module}`)
  }
}

// 监听窗口大小变化
const handleResize = () => {
  incomeChart?.resize()
}

onMounted(() => {
  fetchFinanceOverview()
  initIncomeChart()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  incomeChart?.dispose()
})
</script>

<style lang="scss" scoped>
.finance-container {
  padding: 20px;
  
  .finance-overview {
    margin-bottom: 20px;
    
    .overview-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .overview-content {
      text-align: center;
      
      .amount {
        font-size: 24px;
        font-weight: bold;
        color: #303133;
        margin: 10px 0;
      }
      
      .compare {
        font-size: 14px;
        color: #909399;
        
        .up {
          color: #67C23A;
        }
        
        .down {
          color: #F56C6C;
        }
      }
    }
  }
  
  .module-nav {
    margin-bottom: 20px;
    
    .module-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      cursor: pointer;
      padding: 20px 0;
      
      .el-icon {
        font-size: 32px;
        margin-bottom: 10px;
        color: #409EFF;
      }
      
      span {
        font-size: 16px;
        color: #303133;
      }
      
      &:hover {
        .el-icon {
          color: #66b1ff;
        }
      }
    }
  }
  
  .chart-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .chart-container {
      height: 400px;
    }
  }
}
</style> 